package bot

import (
	"bytes"
	"crypto/md5"
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"image/color"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/fogleman/gg"
	"github.com/sirupsen/logrus"
)

// SendImg 发送图片
func SendImg(botKey, title string, lines ...string) error {
	fontSize := 16
	space := 20    // 左右留白
	lineSpace := 3 // 行间距
	// w := 300       // len(lines[0])*fontSize + space*2

	dc := gg.NewContext(1024, 1024)
	dc.LoadFontFace("./fonts/msyh.ttc", float64(fontSize))
	w, _ := dc.MeasureString(title)
	for _, s := range lines {
		sW, _ := dc.MeasureString(s)
		if sW > w {
			w = sW
		}
	}
	width := int(w) + space
	if len(title) > 0 {
		dc = gg.NewContext(width, lineSpace+(fontSize+lineSpace)*len(lines)+lineSpace+fontSize+lineSpace+10)
	} else {
		dc = gg.NewContext(width, lineSpace+(fontSize+lineSpace)*len(lines)+lineSpace)
	}
	dc.LoadFontFace("./fonts/msyh.ttc", float64(fontSize))
	dc.SetColor(color.White)
	dc.Clear()
	var start = 0
	// title
	if len(title) > 0 {
		dc.SetColor(color.RGBA{0, 225, 0, 245}) //color.RGBA{255, 140, 0, 255})
		sW, _ := dc.MeasureString(title)
		start = lineSpace + fontSize + 5
		dc.DrawString(title, (float64(width)-sW)/2, float64(start)) // 增加行距
		start += 5
	}
	// msg
	dc.SetColor(color.Black)
	for i, s := range lines {
		sW, _ := dc.MeasureString(s)
		dc.DrawString(s, (float64(width)-sW)/2, float64(start+(lineSpace+fontSize)*(i+1)))
	}
	dc.SavePNG("./test.png")
	f, _ := os.Open("./test.png")
	defer f.Close()
	sta, _ := f.Stat()
	buf := make([]byte, sta.Size())
	f.Read(buf)
	imgBase64 := base64.StdEncoding.EncodeToString(buf)
	imgMd5 := md5.Sum(buf)
	imgMd5Str := fmt.Sprintf("%x", imgMd5)
	msgStr := `
{
	"msgtype": "image",
	"image": {
		"base64": "%s",
		"md5": "%s"
	}
}
	`
	msgStr = fmt.Sprintf(msgStr, imgBase64, imgMd5Str)
	return send(botKey, msgStr)
}

// SendMsg 发送消息
// botKey 机器人的Key
func SendMsg(botKey, title, warn, msg, comment string) error {
	// h.Message = `实时新增用户反馈<font color=\"warning\">132例</font>，请相关同事注意。\n
	// >类型:<font color=\"comment\">用户反馈</font> \n
	// >普通用户反馈:<font color=\"comment\">117例</font> \n
	// >VIP用户反馈:<font color=\"comment\">15例</font>`

	if len(msg) == 0 {
		return errors.New("没有消息体")
	}

	// 处理数据格式
	var msgStr string
	if len(warn) > 0 {
		msgStr += fmt.Sprintf(`<font color=\"warning\">%s</font>\r\n`, warn)
	}
	if len(title) > 0 {
		msgStr += fmt.Sprintf(`<font color=\"info\">%s</font>\r\n`, title)
	}
	if len(msg) > 0 {
		msgStr += fmt.Sprintf(`%s\r\n`, msg)
	}
	if len(comment) > 0 {
		msgStr += fmt.Sprintf(`<font color=\"comment\">%s</font>\r\n`, comment)
	}
	msgStr = strings.Trim(msgStr, "\r\n")
	msgStr = fmt.Sprintf(`
	{
		"msgtype": "markdown",
		"markdown": {
			"content": "%s"
		}
	}`, msgStr)

	// if msgType == "news" {
	// 	msgStr = MsgNews(h)
	// }
	logrus.Info("发送的消息是：", msgStr)
	return send(botKey, msgStr)
}

func send(botKey, msgStr string) error {
	// 发送http请求
	client := &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}
	resp, err := client.Post("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+botKey, "application/json", bytes.NewBuffer([]byte(msgStr)))
	if err != nil {
		return errors.New("post error " + err.Error())
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	res := make(map[string]interface{})
	json.Unmarshal(body, &res)
	if res["errcode"].(float64) == 0 {
		return nil
	}
	logrus.Error("send error:" + string(body))
	return errors.New(string(body))
}
